package com.dalei.vdsmanager.security.service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.springframework.dao.DataAccessException;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UserDetailsService;
import org.springframework.security.userdetails.UsernameNotFoundException;

import com.dalei.vdsmanager.security.dao.Role;
import com.dalei.vdsmanager.security.dao.User;
import com.dalei.vdsmanager.security.dao.UserDao;

public class UserDetailsServiceImpl implements UserDetailsService, Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 3067253879418152214L;

	private UserDao userDao;

	public UserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {
		// TODO Auto-generated method stub
		User user = userDao.findUserByUserName(username);
		if (user != null) {
			return new UserDetailsImpl(user);
		} else {
			throw new UsernameNotFoundException("User " + username
					+ " Not Found!");
		}
	}

	public class UserDetailsImpl implements UserDetails {

		/**
		 * 
		 */
		private static final long serialVersionUID = -1108782834708787136L;

		private User user;

		public UserDetailsImpl(User user) {
			// TODO Auto-generated constructor stub
			this.user = user;
		}

		@Override
		public GrantedAuthority[] getAuthorities() {
			// TODO Auto-generated method stub
			List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
			Set<Role> roles = user.getRoles();
			for (Role role : roles) {
				grantedAuthorities.add(new GrantedAuthorityImpl(role
						.getRoleName()));
			}
			return grantedAuthorities
					.toArray(new GrantedAuthority[roles.size()]);
		}

		@Override
		public String getPassword() {
			// TODO Auto-generated method stub
			return user.getPassword();
		}

		@Override
		public String getUsername() {
			// TODO Auto-generated method stub
			return user.getUser();
		}

		@Override
		public boolean isAccountNonExpired() {
			// TODO Auto-generated method stub
			return true;
		}

		@Override
		public boolean isAccountNonLocked() {
			// TODO Auto-generated method stub
			return true;
		}

		@Override
		public boolean isCredentialsNonExpired() {
			// TODO Auto-generated method stub
			return true;
		}

		@Override
		public boolean isEnabled() {
			// TODO Auto-generated method stub
			return user.getIsEnabled();
		}

	}
}
